﻿using System.Threading;
using DM4;
using sscore;
using System;
using System.Collections.Generic;
using sscore.Utils;
using System.Text.RegularExpressions;
using System.IO;
using sscore.Requests;

namespace IL
{
    public class IL : ModuleBase
    {
        private readonly string _searchUrl;
        private readonly string _offenderLink;
        private readonly string _imageLink;
        private const string StateName = "IL";
        private ResultFile _imagesResultFile;
        string _jsessionid, _cftoken, _cfid, _firstpage, _lastpage;

        const string ErrorCalculateFirstLastPage = "Unable to calculate the value of the first and last page";

        public IL()
        {
            //initialize main system constants
            ModuleCode = "SO_IL";
            Description = "IL Sex Offenders";
            Version = "1.0";

            //for creating sessions
            StartParam = 1;
            StopParam = 1200;

            //initialize help 
            AddToHelp(DM4Consts.StartPosition, String.Format("{0}...{1}", StartParam, StopParam));
            AddToHelp(DM4Consts.EndPositon, String.Format("{0}...{1}", StartParam, StopParam));

            AddToHelp(DM4Consts.IsDownload, "true|false");
            AddToHelp(DM4Consts.IsDownloadImg, "true|false");
            AddToHelp(DM4Consts.InsertToDb, "false|true", "(Expected: servername, dbname)");
            AddToHelp(DM4Consts.ServerName, "");
            AddToHelp(DM4Consts.DbName, "");
            AddToHelp(DM4Consts.IsClearDb, "false|true");
            AddToHelp(DM4Consts.TestParam, "false|true");

            RootUrl = "http://www.isp.state.il.us/";
            _searchUrl = RootUrl + "sor/offenderlist.cfm?CFID={0}&CFTOKEN={1}&jsessionid={2}";
            _offenderLink = RootUrl + "sor/offenderdetails.cfm?SORID={0}&CFID={1}&CFTOKEN={2}&jsessionid={3}";
            _imageLink = RootUrl + "sor/photos/{0}.jpg";
        }

        private void SetParametersDefaults()
        {
            Params.CreateBooleanParam(DM4Consts.IsDownload, true);
            Params.CreateBooleanParam(DM4Consts.IsDownloadImg, true);
            Params.CreateBooleanParam(DM4Consts.InsertToDb, false);
            Params.CreateBooleanParam(DM4Consts.IsClearDb, false);
            Params.CreateStringParam(DM4Consts.DbName, "");
            Params.CreateStringParam(DM4Consts.ServerName, "");
            Params.CreateIntegerParam(DM4Consts.StartPosition, StartParam);
            Params.CreateIntegerParam(DM4Consts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
            Params.CreateIntegerParam(DM4Consts.EndPositon, StopParam);
            Params.CreateIntegerParam(DM4Consts.LastRecord, 0);
        }

        public override OperationResult Init(IDM4Core iCore, DmTaskParams param)
        {
            //use basic initialization sequence
            base.Init(iCore, param);

            SetParametersDefaults();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult Start()
        {
            DoWork();
            return new OperationResult { Result = DM4Consts.Ok };
        }

        public override OperationResult DoWork()
        {
            OperationResult or = new OperationResult { Result = DM4Consts.ErrorUnknown };

            if (!Ct.IsCancellationRequested)
            {
                WriteLog("Start parameters:", MessageType.Warning);
                foreach (KeyValuePair<string, string> kvp in Params.GetDictionary()) //get all existing parameters
                    WriteLog(String.Format("Key = {0}, Value = {1}", kvp.Key, kvp.Value), MessageType.Warning);

                if (Params.GetBooleanParam(DM4Consts.IsDownload))
                    Load();

                if (Params.GetBooleanParam(DM4Consts.InsertToDb))
                    if ((Params.GetStringParam(DM4Consts.DbName) == "") || (Params.GetStringParam(DM4Consts.ServerName) == ""))
                    {
                        or.Message = String.Format("{0} or {1} is empty", DM4Consts.DbName, DM4Consts.ServerName);
                        ResultCode = DM4Consts.SessionResultCodeError;
                        ResultMessage = or.Message;
                        UpdateStatus(DmConsts.Error);
                        WriteErrorLog(or.Message); //writting to error and session log   

                        return or;
                    }
                    else
                    {
                        //insert offenders to db 
                        UpdateStatus(DM4Consts.SessionInsertToDb);

                        Offenders.OffInsertToDatabase(StateName, Params.GetStringParam(DmConsts.DbName),
                             Params.GetStringParam(DmConsts.ServerName), ResultDir, Params.GetBooleanParam(DmConsts.IsClearDb),
                             WriteLog);

                    }

                //check if need abort task
                if (Ct.IsCancellationRequested)
                {
                    ResultCode = DM4Consts.SessionResultTerminateByUser;
                    ResultMessage = "Session terminated by user";
                    UpdateStatus(DM4Consts.SessionWait);
                    WriteLog("Session aborted by user", MessageType.Cool);
                }
                else
                {
                    UpdateProgress(1);
                    ResultCode = DM4Consts.SessionResultCodeOk;
                    ResultMessage = String.Format("Session complete, errors : {0}, records : {1}", TaskParams.ErrorCount, TaskParams.RecordCount);
                    UpdateStatus(DM4Consts.SessionComplete);
                    WriteLog("------------Finish----------------", MessageType.Cool);
                }
            }
            else
            {
                ResultCode = DM4Consts.SessionResultTerminateByUser;
                ResultMessage = "Session terminated by user";
                UpdateStatus(DM4Consts.SessionWait);
                WriteLog("Session aborted by user", MessageType.Cool);
            }


            return or;
        }

        private void Load()
        {
            string resultFileName = String.Format("{0}\\{1}.{2}", ResultDir, TaskParams.SessionId, DmConsts.ResultFilesExtension);
            bool workFlag = true;

            ResultFile = new ResultFile(resultFileName, OffendersResult.GetHeader());
            _imagesResultFile = new ResultFile(String.Format("{0}\\{1}_images.{2}", ResultDir, TaskParams.SessionId, DM4Consts.ResultFilesExtension), "FileName|FileUrl");
            try
            {
                while (workFlag)
                {
                    //рабочий цикл
                    string error;

                    try
                    {
                        error = "";  //Required!!  /*if (!String.IsNullOrEmpty(error)) --> restart thread; else --> download finished*/

                        WriteLog("Start download...");
                        Searching();
                    }
                    catch (Exception e)
                    {
                        error = e.Message;
                    }

                    if (!String.IsNullOrEmpty(error))
                    {
                        Thread.Sleep(30000);
                        WriteErrorLog(error);
                        WriteLog("Try continue work...", MessageType.Warning);
                    }
                    else
                    {
                        workFlag = false;  //все нормально откачало, заканчиваем работу
                    }
                }
            }
            finally
            {
                ResultFile.Close();
                _imagesResultFile.Close();
            }
        }

        private void GetCookies()
        {
            string html = GetRequest.ReturnCookies(RootUrl + "sor/sor.cfm", Rpm);
            Rpm.Cookies = RegExpr.Parse(Rpm.Cookies, @"(?si:(JSESSIONID=[^;]+))");
            CheckPage(html);

            if (html.Contains("DISCLAIMER"))
                html = PostRequest.RefererWithCookies(RootUrl + "sor/sor.cfm", RootUrl + "sor/sor.cfm", "Agree=I+Agree", Rpm);
            CheckPage(html);

            const string rexp = @"(?si:\x3FCFID\x3D([\S]+)\x26CFTOKEN\x3D([\S]+)\x26jsessionid\x3D([\S]+)"")";
            _cfid = RegExpr.Parse(html, rexp);
            _cftoken = RegExpr.Parse(html, rexp, 2);
            _jsessionid = RegExpr.Parse(html, rexp, 3);

            Rpm.Cookies = "JSESSIONID=" + _jsessionid;
        }

        private void CheckPage(string html)
        {
            if (string.IsNullOrEmpty(html)
                || RegExpr.IsMatch(html, @"(?si:Access Denied)")
                || !RegExpr.IsMatch(html, @"(?si:hd_title_section-copy.jpg)"))
                throw new Exception(DmConsts.ExcNeedRestart);
        }

        private void Searching()
        {
            if (Test)
            {
                Params.SetIntegerParam(DmConsts.LastPosition, Params.GetIntegerParam(DmConsts.StartPosition));
                Params.SetIntegerParam(DmConsts.EndPositon, Params.GetIntegerParam(DmConsts.StartPosition));
            }

            if (Params.GetIntegerParam(DmConsts.EndPositon) > StopParam)
                Params.SetIntegerParam(DmConsts.EndPositon, StopParam);

            if (Params.GetIntegerParam(DmConsts.LastPosition) < StartParam)
                Params.SetIntegerParam(DmConsts.LastPosition, StartParam);


            GetCookies();

            WriteLog("navigate to first offenders page; get values for firstpage and lastpage");

            string html = PostRequest.RefererWithCookies(RootUrl + "sor/offenderlist.cfm",
                RootUrl + "sor/sor.cfm",
                "lastname=&city=&zipcode=&county=&status=X&cso=XYZ&result=25&Submit=Find",
                Rpm);
            CheckPage(html);

            string searchUrl = string.Format(_searchUrl, _cfid, _cftoken, _jsessionid);
            _firstpage = RegExpr.Parse(html, @"(?si:value=""([\d]+)"" name=""pagenum_offendersfirst"")");
            _lastpage = RegExpr.Parse(html, @"(?si:value=""([\d]+)"" name=""pagenum_offenderslast"")");

            if (_firstpage == "" || _lastpage == "")
                throw new Exception(ErrorCalculateFirstLastPage);

            WriteLog(String.Format("firstpage [{0}];  lastpage [{1}]", _firstpage, _lastpage));

            if (Params.GetIntegerParam(DmConsts.EndPositon) > Convert.ToInt32(_lastpage))
                Params.SetIntegerParam(DmConsts.EndPositon, Convert.ToInt32(_lastpage));

            if (Params.GetIntegerParam(DmConsts.LastPosition) != 1)
            {
                WriteLog(String.Format("navigate to page {0} ", Params.GetIntegerParam(DmConsts.LastPosition)));
                html = PostRequest.RefererWithCookies(searchUrl, searchUrl, GetQueryString(), Rpm);
                CheckPage(html);
            }
            //parse first result page
            ParseResultPage(html);

            //loop by next result pages
            do
            {
                if (Ct.IsCancellationRequested)
                    break;

                if (!html.Contains("timages/next.gif")) break;

                Params.SetIntegerParam(DmConsts.LastPosition, Params.GetIntegerParam(DmConsts.LastPosition) + 1);
                WriteLog(String.Format("navigate to page [{0}] ", Params.GetIntegerParam(DmConsts.LastPosition)));
                html = PostRequest.RefererWithCookies(searchUrl, searchUrl, GetQueryString(), Rpm);
                CheckPage(html);

                ParseResultPage(html);
                UpdateProgress();

            } while (true);
        }

        private void ParseResultPage(string html)
        {
            html = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(html.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));

            if (!RegExpr.IsMatch(html, @"(?si:>\s*Illinois\s*State\s*Police\s*<)"))
                throw new Exception(String.Format("Result page: {0}{1}{2}", DmConsts.ExcNeedRestart, Environment.NewLine, html));

            MatchCollection mc = RegExpr.ParseMatchCollection(html, @"(?si:""self.location='offenderdetails.cfm\?SORID=([\S]+)&)");
            WriteLog(String.Format("found [{0}] matches", mc.Count));
            if (mc.Count == 0)
                throw new Exception(DmConsts.ExcNeedRestart + Environment.NewLine + html);

            List<string> list = new List<string>();

            foreach (Match matchLoc in mc)
                if (!list.Contains(matchLoc.Groups[1].Value))
                    list.Add(matchLoc.Groups[1].Value);

            WriteLog(String.Format("found [{0}] id[s]", list.Count));

            for (int i = Params.GetIntegerParam(DmConsts.LastRecord); i < list.Count; i++)
            {
                //check if need abort task
                if (Ct.IsCancellationRequested)
                    break;

                Params.SetIntegerParam(DmConsts.LastRecord, i);
                string lookupKey = list[i];
                string offenderHtml = GetRequest.WithCookies(string.Format(_offenderLink, lookupKey, _cfid, _cftoken, _jsessionid), Rpm);
                WriteLog(String.Format("ParseOffender [{0}][{1}]", Params.GetIntegerParam(DmConsts.LastRecord), lookupKey));

                if (!RegExpr.IsMatch(offenderHtml, @"(?si:>\s*Name\s*:\s*<)"))
                    throw new Exception("Offenders page:" + DmConsts.ExcNeedRestart);

                ParseOffender(offenderHtml, lookupKey);
                UpdateRecordCount(1);
            }
            Params.SetIntegerParam(DmConsts.LastRecord, 0);
        }

        private void ParseOffender(string offenderHtml, string lookupKey)
        {
            offenderHtml = HtmlUtils.KillSpace(HtmlUtils.ReplaceSpecSymbols(offenderHtml.Replace("\r\n", " ").Replace("\t", " ").Replace("\r", " ").Replace("\n", " ")));
            using (OffendersResult or = new OffendersResult())
            {
                or.Source_State = StateName;
                or.offenderLink = string.Format(_offenderLink, lookupKey, _cfid, _cftoken, _jsessionid);
                or.Source_id = lookupKey;

                or.fullname = RegExpr.Parse(offenderHtml, @"(?si:Name\s*:\s*</td>\s*<td[^<>]*?>(.*?)</td>)").Trim();
                or.Birthdate = RegExpr.Parse(offenderHtml, @"(?si:Date of Birth\s*:\s*</td>\s*<td[^<>]*?>(.*?)</td>)").Trim();
                or.height = RegExpr.Parse(offenderHtml, @"(?si:Height\s*:\s*</td>\s*<td>(.*?)</td>)").Trim();
                or.weight = RegExpr.Parse(offenderHtml, @"(?si:Weight\s*:\s*</td>\s*<td>(.*?)</td>)").Trim();
                or.sex = RegExpr.Parse(offenderHtml, @"(?si:Sex\s*:\s*</td>\s*<td>(.*?)</td>)").Trim();
                or.Ethnicity = RegExpr.Parse(offenderHtml, @"(?si:Race\s*:\s*</td>\s*<td>(.*?)</td>)").Trim();

                foreach (Match matchLoc in RegExpr.ParseMatchCollection(
                   HtmlUtils.KillSpace(RegExpUtils.DeleteTag(RegExpr.Parse(offenderHtml,
                       @"(?si:Address\s*:\s*</td>(.*?)<td colspan=""8"" height=""1"" class=""tmpl_headerbackgroundcolor"">)"))),
                   "(?si:<td>(.*?)</td>)"))
                {
                    if (matchLoc.Groups[1].Value.Trim() != "")
                        if (or.Address == "")
                            or.Address += matchLoc.Groups[1].Value.Trim();
                        else
                            or.Address += "@" + matchLoc.Groups[1].Value.Trim();
                }

                or.Status = RegExpr.Parse(offenderHtml, @"(?si:<font size=""\x2B1"">([^<>]+)</font>)").Trim();
                if (offenderHtml.Contains("Sexual Predator"))
                    or.Risk = "Sexual Predator";
                else if (offenderHtml.Contains("Sexually Violent"))
                    or.Risk = "Sexually Violent";

                const string crimeCaption = "Crime; County of Conviction~";
                int iCrime = 0;
                foreach (Match matchLoc in RegExpr.ParseMatchCollection(offenderHtml, @"(?si:<td nowrap>(.*?)</td>)"))
                {
                    or.Crime += matchLoc.Groups[1].Value.Trim() + ";";
                    try
                    {
                        or.Crime += RegExpr.ParseMatchCollection(offenderHtml,
                            @"(?si:County of Conviction\s*:\s*</td>\s*<td class=""allcaps"">(.*?)</td>)")[iCrime].Groups[1].Value.Trim() + "~";
                    }
                    catch
                    {
                        or.Crime += "~";
                    }

                    iCrime++;
                }
                if (or.Crime != "") or.Crime = crimeCaption + or.Crime;

                if (Params.GetBooleanParam(DmConsts.IsDownloadImg))
                {
                    int iImg = 0;
                    MatchCollection mcImg = RegExpr.ParseMatchCollection(offenderHtml, @"(?si:<img src=""photos/([\S]+).jpg"" alt=)");

                    if (mcImg.Count > 0)
                        foreach (Match m in mcImg)
                        {
                            string imgName;
                            if (iImg == 0)
                            {
                                or.Image_ID = Guid.NewGuid().ToString();
                                or.ImageLink = string.Format(_imageLink, m.Groups[1].Value);
                                imgName = String.Format("{0}\\{1}\\{2}.jpg", ResultDir, DmConsts.PhotosDir, or.Image_ID);
                            }
                            else
                                imgName = String.Format("{0}\\{1}\\{2}_{3}.jpg", ResultDir, DmConsts.PhotosDir, or.Image_ID, iImg);


                            Offenders.DownloadImageWithExceptions(_imagesResultFile, imgName, string.Format(_imageLink, m.Groups[1].Value), TaskParams.SessionId);
                            iImg++;
                        }//foreach (Match m in mcImg)
                }
                if (or.Image_ID != "") or.Image_ID += ".jpg";
                if (or.Image_ID != "" && !File.Exists(String.Format("{0}\\{1}\\{2}", ResultDir, DmConsts.PhotosDir, or.Image_ID)))
                    throw new Exception(DmConsts.ExcImgNotFound);

                ResultFile.Write(or.GetValues());
            }
        }

        private string GetQueryString()
        {
            return
                "Ci=&Co=&la=&st=&re=&zi=&print=0&City=&County=&lastname=&status=X&cso=XYZ&result=25&zipcode="
                + "&pagenum_offendersnext=" + Params.GetIntegerParam(DmConsts.LastPosition)
                + "&pagenum_offendersfirst=" + _firstpage
                + "&pagenum_offenderslast=" + _lastpage
                + "&pagenum_offendersprev=" + _firstpage
                + "&pagenum_offenders=" + Params.GetIntegerParam(DmConsts.LastPosition)
                + "&Next.x=16&Next.y=16";
        }

        private void UpdateProgress()
        {
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.LastPosition) > Params.GetIntegerParam(DmConsts.EndPositon))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.LastPosition), Params.GetIntegerParam(DmConsts.EndPositon),
                    DmConsts.StartPosition, DmConsts.EndPositon));
            if (Params.GetIntegerParam(DmConsts.StartPosition) > Params.GetIntegerParam(DmConsts.LastPosition))
                throw new Exception(String.Format("Invalid parameters {2}[{0}]; {3} [{1}]",
                    Params.GetIntegerParam(DmConsts.StartPosition), Params.GetIntegerParam(DmConsts.LastPosition),
                    DmConsts.StartPosition, DmConsts.LastPosition));
            UpdateProgress(((double)(Params.GetIntegerParam(DmConsts.LastPosition) - Params.GetIntegerParam(DmConsts.StartPosition))) / (Params.GetIntegerParam(DmConsts.EndPositon) - Params.GetIntegerParam(DmConsts.StartPosition) + 1));
        }
    }
}
